import 'package:flutter/material.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:edu_assistant/api/data_service.dart';
import 'package:edu_assistant/model/media_item_entity.dart';
// import 'package:edu_assistant/widgets/cached_video_view_player.dart';
import 'package:edu_assistant/widgets/video_view_player.dart';
// import 'package:edu_assistant/widgets/video_view_player_kit.dart';
import 'package:edu_assistant/widgets/common_image_view.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import '../model/filter_condition.dart';

class MediaPage extends StatefulWidget {
  const MediaPage({Key? key}) : super(key: key);

  @override
  State<MediaPage> createState() => _MediaPageState();
}

class _MediaPageState extends State<MediaPage>
    with AutomaticKeepAliveClientMixin {
  var _scaffoldKey = new GlobalKey<ScaffoldState>();
  GlobalKey _stackKey = GlobalKey();
  String _dropdownMenuChange = '';
  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();
  List<String> titles = ["文件类型"];
  List<Widget> listWidget = [];
  List<String> types = ["全部", "视频", "图片", "PDF"];
  String fileType = "";
  int _count = 0;
  int page = 1;
  int size = 10;
  bool lastPage = true;
  List<MediaItemEntity> dataList = [];
  late EasyRefreshController _controller;
  List<FilterCondition> _fileTypeConditions = [];
  late FilterCondition _selectFileTypeCondition;
  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
    _fileTypeConditions.add(FilterCondition(name: '全部',value: "", isSelected: true));
    _fileTypeConditions.add(FilterCondition(name: '视频',value: "video/mp4", isSelected: false));
    _fileTypeConditions.add(FilterCondition(name: '图片',value: "image/jpeg", isSelected: false));
    _fileTypeConditions.add(FilterCondition(name: 'PDF',value: "application/pdf", isSelected: false));
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  Widget buildCard(int index) {
    MediaItemEntity mediaItemEntity = dataList[index];
    ListTile listTile = ListTile(
      contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
      leading: Container(
        padding: EdgeInsets.only(right: 12.0),
        decoration: BoxDecoration(
          border: Border(
            right: BorderSide(width: 1.0, color: Colors.black12),
          ),
        ),
        child: CommonImageView(
            url: mediaItemEntity.mediaImage, height: 180, width: 100),
      ),
      title: Text(
        mediaItemEntity.mediaName ?? "",
        style: TextStyle(
            color: Colors.blueGrey, fontSize: 12, fontWeight: FontWeight.bold),
      ),
      // subtitle: Text("中级", style: TextStyle(color: Colors.white)),
      trailing: Icon(
        Icons.keyboard_arrow_right,
        color: Colors.blue,
        size: 30.0,
      ),
    );
    return GestureDetector(
      onTap: () {
        // 点击时打开图片预览
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => VideoPlayerScreen(
              url: mediaItemEntity.mediaUrl!,
              title: mediaItemEntity.mediaName ?? "",
            ),
          ),
        );
      },
      child: listTile,
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      key: _scaffoldKey,
      appBar: PreferredSize(
        child: AppBar(
          backgroundColor: Theme.of(context).primaryColor,
          elevation: 0,
        ),
        preferredSize: Size.fromHeight(0),
      ),
      backgroundColor: Colors.white,
      body: Stack(
        key: _stackKey,
        children: <Widget>[
          Column(
            children: <Widget>[
              Container(
                width: MediaQuery.of(context).size.width,
                height: 44,
                color: Theme.of(context).primaryColor,
                alignment: Alignment.center,
                child: Text(
                  '媒体列表',
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              // 下拉菜单头部
              GZXDropDownHeader(
                // 下拉的头部项，目前每一项，只能自定义显示的文字、图标、图标大小修改
                items: [
                  GZXDropDownHeaderItem(
                    titles[0],
                  )
                ],
                // GZXDropDownHeader对应第一父级Stack的key
                stackKey: _stackKey,
                // controller用于控制menu的显示或隐藏
                controller: _dropdownMenuController,
                // 当点击头部项的事件，在这里可以进行页面跳转或openEndDrawer
                onItemTap: (index) {
                  if (index == 3) {
                    _dropdownMenuController.hide();
                    _scaffoldKey.currentState!.openEndDrawer();
                  }
                },
                style: TextStyle(color: Color(0xFF666666), fontSize: 14),
                // 下拉时文字样式
                dropDownStyle: TextStyle(
                  fontSize: 14,
                  color: Theme.of(context).primaryColor,
                ),
              ),
              //列表内容
              Expanded(
                child: _getFileListWidget(),
              ),
            ],
          ),
          GZXDropDownMenu(
            // controller用于控制menu的显示或隐藏
            controller: _dropdownMenuController,
            // 下拉菜单显示或隐藏动画时长
            animationMilliseconds: 300,
            // 下拉后遮罩颜色
            maskColor: Theme.of(context).primaryColor.withOpacity(0.5),
            dropdownMenuChanging: (isShow, index) {
              setState(() {
                _dropdownMenuChange = '(正在${isShow ? '显示' : '隐藏'}$index)';
                print(_dropdownMenuChange);
              });
            },
            dropdownMenuChanged: (isShow, index) {
              setState(() {
                _dropdownMenuChange = '(已经${isShow ? '显示' : '隐藏'}$index)';
                print(_dropdownMenuChange);
              });
            },
            // 下拉菜单，高度自定义，你想显示什么就显示什么，完全由你决定，你只需要在选择后调用_dropdownMenuController.hide();即可
            menus: [
              GZXDropdownMenuBuilder(
                dropDownHeight: _fileTypeConditions.length * 40,
                dropDownWidget: _buildConditionListWidget(
                  _fileTypeConditions,
                  (selectValue) {
                    _selectFileTypeCondition = selectValue;
                    fileType = selectValue.value;
                    titles[0] = _selectFileTypeCondition.name;
                    _dropdownMenuController.hide();
                    setState(() {});
                    _controller.callRefresh();
                  },
                ),
              ),
            ],
          ),
          // 下拉菜单，注意GZXDropDownMenu目前只能在Stack内，后续有时间会改进，以及支持CustomScrollView和NestedScrollView
        ],
      ),
    );
  }

  _buildConditionListWidget(
    items,
    void itemOnTap(FilterCondition filterCondition),
  ) {
    return ListView.separated(
      shrinkWrap: true,
      scrollDirection: Axis.vertical,
      itemCount: items.length,
      // item 的个数
      separatorBuilder: (BuildContext context, int index) =>
          Divider(height: 1.0),
      // 添加分割线
      itemBuilder: (BuildContext context, int index) {
        return gestureDetector(items, index, itemOnTap, context);
      },
    );
  }

  GestureDetector gestureDetector(items, int index,
      void itemOnTap(FilterCondition condition), BuildContext context) {
    FilterCondition filterCondition = items[index];
    return GestureDetector(
      onTap: () {
        for (var value in items) {
          value.isSelected = false;
        }
        filterCondition.isSelected = true;

        itemOnTap(filterCondition);
      },
      child: Container(
        //            color: Colors.blue,
        height: 40,
        child: Row(
          children: <Widget>[
            SizedBox(
              width: 16,
            ),
            Expanded(
              child: Text(
                filterCondition.name,
                style: TextStyle(
                  color: filterCondition.isSelected
                      ? Theme.of(context).primaryColor
                      : Colors.black,
                ),
              ),
            ),
            filterCondition.isSelected
                ? Icon(
                    Icons.check,
                    color: Theme.of(context).primaryColor,
                    size: 16,
                  )
                : SizedBox(),
            SizedBox(
              width: 16,
            ),
          ],
        ),
      ),
    );
  }
  Widget _getFileListWidget() {
    return EasyRefresh(
      controller: _controller,
      refreshOnStart: true,
      header: const ClassicHeader(
          showMessage: false,
          dragText: "下拉刷新",
          armedText: "释放刷新",
          readyText: "刷新中",
          processingText: "刷新中",
          processedText: "刷新完成"),
      footer: const ClassicFooter(
          showMessage: false,
          dragText: "上划加载",
          armedText: "释放加载",
          readyText: "加载中",
          processingText: "加载中",
          processedText: "加载完成",
          noMoreText: "--到底啦--"),
      onRefresh: () async {
        page = 1;
        await DataService.getMediaPage(
            {"page": page, "size": size, "fileType": fileType}).then((value) {
          int totalPages = (value.total! + size - 1) ~/ size;
          if (totalPages == 1) {
            lastPage = true;
          } else {
            lastPage = false;
            page++;
          }
          dataList.clear();
          value.rows?.forEach((element) {
            dataList.add(element);
          });
          _count = dataList.length;
          setState(() {});
        });
        _controller.finishRefresh();
        _controller.resetFooter();
      },
      onLoad: () async {
        await DataService.getMediaPage(
            {"page": page, "size": size, "fileType": fileType}).then((value) {
          int totalPages = (value.total! + size - 1) ~/ size;
          if (totalPages <= page) {
            lastPage = true;
          } else {
            lastPage = false;
            page++;
          }
          value.rows?.forEach((element) {
            dataList.add(element);
          });
          _count = dataList.length;
          setState(() {});
        });
        _controller.finishLoad(
            lastPage ? IndicatorResult.noMore : IndicatorResult.success);
      },
      child: ListView.builder(
        itemBuilder: (context, index) {
          return Card(
            elevation: 0.2,
            margin: EdgeInsets.symmetric(horizontal: 1.0, vertical: 3.0),
            child: Container(
              decoration:
              BoxDecoration(color: Color.fromRGBO(250, 240, 240, 0.9)),
              child: buildCard(index),
            ),
          );
        },
        itemCount: _count,
      ),
    );
  }
  @override
  bool get wantKeepAlive => true;
}
